//
//  UserRegisterViewController.m
//  DSYDouban
//
//  Created by dllo on 16/1/2.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "UserRegisterViewController.h"
#import "LabelTextView.h"
#import "DBManager.h"

@interface UserRegisterViewController ()<UITextFieldDelegate>

@property (nonatomic, retain) LabelTextView *userLTView;

@property (nonatomic, retain) LabelTextView *passLTView;

@property (nonatomic, retain) LabelTextView *rePassLTView;

@property (nonatomic, retain) LabelTextView *emailLTView;

@property (nonatomic, retain) LabelTextView *phoneLTView;

@end

@implementation UserRegisterViewController

- (void)dealloc
{
    [_userLTView release];
    [_passLTView release];
    [_rePassLTView release];
    [_emailLTView release];
    [_phoneLTView release];
    
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"注册";
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    
    self.userLTView = [[LabelTextView alloc] initWithFrame:CGRectMake(15, 30, self.view.frame.size.width - 60, 35)];
    [self.view addSubview:_userLTView];
    _userLTView.LTLabel.text = @"用  户  名: ";
    _userLTView.LTTextField.placeholder = @"请输入用户名";
    _userLTView.LTTextField.delegate = self;
    [_userLTView release];
    
    self.passLTView = [[LabelTextView alloc] initWithFrame:CGRectMake(15, 75, self.view.frame.size.width - 60, 35)];
    [self.view addSubview:_passLTView];
    _passLTView.LTLabel.text = @"密        码: ";
    _passLTView.LTTextField.placeholder = @"请输入密码";
    _passLTView.LTTextField.secureTextEntry = YES;
    _passLTView.LTTextField.clearsOnBeginEditing = YES;
    _passLTView.LTTextField.delegate = self;
    [_passLTView release];
    
    self.rePassLTView = [[LabelTextView alloc] initWithFrame:CGRectMake(15, 120, self.view.frame.size.width - 60, 35)];
    [self.view addSubview:_rePassLTView];
    _rePassLTView.LTLabel.text = @"确认密码:";
    _rePassLTView.LTTextField.placeholder = @"再次输入密码";
    _rePassLTView.LTTextField.secureTextEntry = YES;
    _rePassLTView.LTTextField.clearsOnBeginEditing = YES;
    _rePassLTView.LTTextField.delegate = self;
    [_rePassLTView release];
    
    self.emailLTView = [[LabelTextView alloc] initWithFrame:CGRectMake(15, 165, self.view.frame.size.width - 60, 35)];
    [self.view addSubview:_emailLTView];
    _emailLTView.LTLabel.text = @"邮       箱: ";
    _emailLTView.LTTextField.placeholder = @"请输入邮箱";
    _emailLTView.LTTextField.delegate = self;
    [_emailLTView release];
    
    self.phoneLTView = [[LabelTextView alloc] initWithFrame:CGRectMake(15, 210, self.view.frame.size.width - 60, 35)];
    [self.view addSubview:_phoneLTView];
    _phoneLTView.LTLabel.text = @"联系方式";
    _phoneLTView.LTTextField.placeholder = @"请输入联系方式";
    _phoneLTView.LTTextField.keyboardType = UIKeyboardTypeNumberPad;
    [_phoneLTView release];
    
    
    // 添加右侧 "注册" buttonItem
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(registerItemAction:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    [rightItem release];
    
}

- (void)registerItemAction: (UIBarButtonItem *)buttonItem {
    
    // 判断输入是否为空
    NSCharacterSet *sets = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    // 判断文本框输入是否全部为空格
    BOOL userIsEmpty = [[_userLTView.LTTextField.text stringByTrimmingCharactersInSet:sets] length] == 0;
    
    BOOL phoneIsEmpty = [[_phoneLTView.LTTextField.text stringByTrimmingCharactersInSet:sets] length] == 0;
    
    if (userIsEmpty || _userLTView.LTTextField.text.length == 0 || _userLTView.LTTextField.text == nil) {
        NSLog(@"什么都没有输入");
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示消息" message:@"姓名不能为空" preferredStyle:UIAlertControllerStyleAlert];
        
        
        UIAlertAction *OkAlertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_userLTView.LTTextField becomeFirstResponder];
        }];
        UIAlertAction *CancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:OkAlertAction];
        [alert addAction:CancelAction];
        
        // 显示对话框
        [self presentViewController:alert animated:YES completion:nil];
        
    } else if (phoneIsEmpty || _phoneLTView.LTTextField.text.length == 0 || _phoneLTView.LTTextField.text == nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示消息" message:@"号码不能为空" preferredStyle:UIAlertControllerStyleAlert];
        
        
        UIAlertAction *OkAlertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_phoneLTView.LTTextField becomeFirstResponder];
        }];
        UIAlertAction *CancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:OkAlertAction];
        [alert addAction:CancelAction];
        
        // 显示对话框
        [self presentViewController:alert animated:YES completion:nil];
    } else {
    
    
        NSString *username = _userLTView.LTTextField.text;
        NSString *password = _passLTView.LTTextField.text;
        NSString *email = _emailLTView.LTTextField.text;
        NSString *phone = _phoneLTView.LTTextField.text;
        
        
        
        if ([self isSamePassword] == YES) {
            if ([self isRegistered] == NO) { // 当密码一致，没有被注册过
                NSString *sql = [NSString stringWithFormat:@"insert into userInfo (username, password, email, phone, status) values ('%@', '%@', '%@', '%@', 0)", username, password, email, phone];
                // 将用户注册插入数据库中
                [[DBManager createDB] insert:sql];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"消息提示" message:@"注册成功, 是否登录" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    NSMutableArray *array = [[DBManager createDB] select:nil];
                    
                    for (NSMutableDictionary *dic in array) {
                        NSLog(@"%@    %@", [dic objectForKey:@"username"], [dic objectForKey:@"password"]);
                    }
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                
                UIAlertAction *CancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                
                [alert addAction:OKAction];
                [alert addAction:CancelAction];
                
                [self presentViewController:alert animated:YES completion:^{
                }];
            }
        }
        

    }
}

// 检测输入的密码和确认密码是否一致
- (BOOL)isSamePassword {
    if ([_passLTView.LTTextField.text isEqualToString:_rePassLTView.LTTextField.text]) {
        
        return YES;
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"消息提示" message:@"密码不一致" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_rePassLTView.LTTextField becomeFirstResponder];
        }];
        
        [alert addAction:OKAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        
        return NO;
    }
}

// 检测输入的用户名是否被注册
- (BOOL)isRegistered {
    
    // sql查询用户名语句
    NSString *sql = [NSString stringWithFormat:@"select * from userInfo where username = '%@'", _userLTView.LTTextField.text];
    
    NSMutableArray *array = [[DBManager createDB] select:sql];
    
//    NSLog(@"%ld", array.count);
    
    if (array.count <= 0) {  // 如果从数据库中没有找到这个用户
        return NO;
    } else {  // 如果找到用户提示重新输入
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"消息提示" message:@"该用户名已被注册,请重新输入" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_userLTView.LTTextField becomeFirstResponder];
        }];
        
        [alert addAction:OKAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        
        return YES;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    NSLog(@"return");
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
